package com.yupi.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.product.ProductRequest;
import com.yupi.springbootinit.model.vo.ProductVO;
import com.yupi.springbootinit.model.entity.Product;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.ProductService;
import com.yupi.springbootinit.mapper.ProductMapper;
import com.yupi.springbootinit.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{

    @Resource
    private UserService userService;

    /**
     * 展示所有未售商品
     * 同时也可以根据用户的关键词进行搜索
     * @return
     */
    @Override
    public List<ProductVO> listAllProduct(ProductRequest productRequest) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper();
        Long productId = productRequest.getId();
        //传入的商品id不为空，根据商品id查询
        if(productId != null){
            queryWrapper.eq("id",productId);
        }

        //根据搜索关键字查询出对应商品
        String searchText = productRequest.getSearchText();
        if(StringUtils.isNotBlank(searchText)){
            queryWrapper.and(qw ->qw.like("productName",searchText).or().like("context",searchText));
        }

        //根据商品名称搜索商品
        String productName = productRequest.getProductName();
        if(StringUtils.isNotBlank(productName)){
            queryWrapper.like("productName",productName);
        }

        //根据商品描述搜索商品
        String context = productRequest.getContext();
        if(StringUtils.isNotBlank(context)){
            queryWrapper.like("context",context);
        }


        //查询出所有未售商品
        queryWrapper.eq("productStatus",0);

        List<Product> ProductList = this.list(queryWrapper);

        List<ProductVO> productVOList = new ArrayList<>();

        for (Product product : ProductList) {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product, productVO);
            productVOList.add(productVO);
        }

        return productVOList;
    }


    /**
     * 用户创建商品
     * @param product
     * @param loginUser
     * @return
     */
    @Override
    public Long createProduct(Product product, UserVO loginUser) {

        //商品名称 < 20
        String productName = product.getProductName();
        if(StringUtils.isBlank(productName) || productName.length() > 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"商品名称字符错误");
        }

        //商品描述 < 512
        String context = product.getContext();
        if(context.length() > 512){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"商品描述错误");
        }

        //商品价格不能为空
        BigDecimal price = product.getPrice();
        if(price == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"商品价格不能为空");
        }

        //将商品信息插入到product表中
        product.setId(null);
        product.setUserId(loginUser.getId());
        boolean result = this.save(product);
        if(!result){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"商品创建失败");
        }
        return product.getId();

    }

    /**
     * 更新商品信息
     *
     * @param productVO
     * @param request
     * @return
     */
    @Override
    public boolean updateProduct(ProductVO productVO, HttpServletRequest request) {
        UserVO loginUser = userService.getLoginUser(request);
        boolean isAdmin = userService.isAdmin(request);
        Long id = productVO.getId();
        Product product = this.getById(id);
        if(!isAdmin || loginUser.getId() != product.getUserId()){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }



        //指定更新的条件
        LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
        //找出所要更新的商品
        updateWrapper.eq(Product::getId,id);

        //若描述不为空则更新描述
        String context = productVO.getContext();
        if(StringUtils.isNotBlank(context)){
            updateWrapper.set(Product::getContext,context);
        }

        //若价格不为空则更新价格
        BigDecimal price = productVO.getPrice();
        if(price != null){
            updateWrapper.set(Product::getPrice,price);
        }

        //若商品名称不为空则更新商品名称
        String productName = productVO.getProductName();
        if(StringUtils.isNotBlank(productName)){
            updateWrapper.set(Product::getProductName,productName);
        }

        //todo 更新新的商品图片
        String productPhoto = productVO.getProductPhoto();

        boolean result = this.update(updateWrapper);
        return result;
    }

    /**
     * 展示我创建的商品
     * @param loginUser
     * @return
     */
    @Override
    public List<ProductVO> showMyProduct(UserVO loginUser) {
        Long userId = loginUser.getId();
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        List<Product> productList = this.list(queryWrapper);

        List<ProductVO> productVOList = new ArrayList<>();
        for (Product product : productList) {
            ProductVO productVO = new ProductVO();
            BeanUtils.copyProperties(product,productVO);
            productVOList.add(productVO);
        }

        return productVOList;
    }
}




